package com.wandian.executor;

import java.util.LinkedList;
import java.util.Queue;

import com.wandian.util.Log;

/**
 * @author long
 * @Create 2012-11-13 下午3:13:07
 * @QQ 108232706
 * @version 1.0
 * @description AbstractActionQueue
 */
public class AbstractActionQueue
		implements ActionQueue
{
	private Queue<Action> queue = null;
	private Executor executor = null;

	public AbstractActionQueue(Executor executor) {
		this.executor = executor;
		this.queue = new LinkedList<Action>();
	}

	public AbstractActionQueue(Executor executor, Queue<Action> queue) {
		this.executor = executor;
		this.queue = queue;
	}

	public ActionQueue getActionQueue() {
		return this;
	}

	public Queue<Action> getQueue() {
		return this.queue;
	}

	public void enDelayQueue(DelayAction delayAction) {
		this.executor.enDelayQueue(delayAction);
	}

	public void enqueue(Action action) {
		//		Log.debug("入栈");
		boolean canExec = false;
		synchronized (this.queue) {
			this.queue.add(action);
			if (this.queue.size() == 1)
				canExec = true;
			else if (this.queue.size() > 100) {
				Log.warn(toString() + " queue size : " + this.queue.size());
			}
		}

		if (canExec)
			this.executor.execute(action);
	}

	public void dequeue(Action action)
	{
		Action nextAction = null;
		synchronized (this.queue) {
			if (this.queue.size() == 0) {
				Log.error("queue.size() is 0.");
			}
			Action temp = this.queue.remove();
			if (temp != action) {
				Log.error("action queue error. temp " + temp.toString() + ", action : " + action.toString());
			}
			if (this.queue.size() != 0) {
				nextAction = this.queue.peek();
			}
		}

		if (nextAction != null)
			this.executor.execute(nextAction);
	}

	public void clear()
	{
		synchronized (this.queue) {
			this.queue.clear();
		}
	}
}